<template>
  <div class="app-container">
    <!--工具栏-->
    <crudOperation :permission="permission" />
    <div class="head-container"></div>

    <el-dialog
      v-dialog-drag
      style="width: 80vm"
      title="搜索"
      close-on-click-modal
      :visible.sync="crud.props.searchToggle"
      width="70%"
    >
      <el-form size="small" label-width="70px">
        <el-row class="flex flex-wrap">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="月份">
              <el-date-picker
                v-model="date"
                type="month"
                size="small"
                class="date-item"
                style="width: 100%"
                format="yyyy - M"
                value-format="yyyy-M"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="供应商">
              <table-select
                :tableColumns="[
                  { prop: 'code', label: '供应商编码', width: '100' },
                  { prop: 'name', label: '供应商名称', width: '400' },
                ]"
                labelKey="name"
                valueKey="id"
                width="600"
                :value.sync="query.supplierIds"
                placeholder="请选择客户"
                url="api/dropDown/basCustomerList"
              ></table-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="仓库">
              <table-select
                :tableColumns="[
                  { prop: 'code', label: '编码', width: '100' },
                  { prop: 'name', label: '名称', width: '280' },
                ]"
                :value.sync="query.warehouseIds"
                placeholder="请选择仓库"
                url="/api/dropDown/basWarehouseList"
              ></table-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="商品名称">
              <table-select
                :tableColumns="[
                  { prop: 'goodsCode', label: '商品编码', width: '100' },
                  { prop: 'goodsName', label: '商品名称', width: '280' },
                ]"
                labelKey="goodsName"
                valueKey="goodsId"
                :value.sync="query.goodsIds"
                placeholder="请选择商品"
                url="/api/dropDown/basGoodsListForAdd"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="商品品牌">
              <table-select
                :tableColumns="[
                  { prop: 'code', label: '品牌编码', width: '100' },
                  { prop: 'name', label: '品牌名称', width: '280' },
                ]"
                :value.sync="query.goodsBrandIds"
                placeholder="请选择品牌"
                url="/api/dropDown/basGoodsBrandList"
              ></table-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="商品分类">
              <treeselect
                v-model="goodsTypeIds"
                :options="areaList"
                placeholder="商品"
                style="width: 100%"
                :normalizer="normalizer"
                multiple
                @input="getgoodsType"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="小计列">
              <el-checkbox-group
                v-model="groupColumn"
                @change="getChange"
                class="flex flex-row flex-wrap"
              >
                <el-checkbox
                  v-for="item in groupColumnList"
                  :disabled="item.value == ['goodsId', 'warehouseId']"
                  :label="item.value"
                  :key="item.value"
                  :value="item.value"
                  >{{ item.label }}</el-checkbox
                >
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="flex fow-reverse">
          <el-button
            class="filter-item"
            size="mini"
            type="primary"
            @click="queryReport"
            >搜索</el-button
          >
          <el-button
            class="filter-item"
            plain
            size="mini"
            type="primary"
            @click="resetQuery"
            style="margin-right:5px"
            >重置</el-button
          >
        </el-row>
      </el-form>
    </el-dialog>

    <!--表格渲染-->
    <el-table
      ref="table"
      border
      stripe
      show-summary 
      :data="crud.data"
      size="small"
      style="width: 100%"
      height="700"
      v-if="isShowTable"
      @header-dragend="changeColWidth"
      :summary-method="crud.sumRow"
      @row-click="crud.selectRow"
      :row-style="crud.rowClass"
      :row-class-name="crud.tableRowClassName"
      @contextmenu.native="showMenu"
      @selection-change="crud.selectionChangeHandler"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" width="55" label="序号" />
      <el-table-column
        v-if="groupColumnSelectList.includes('goodsId')"
        label="商品编码"
        prop="goodsCode"
      ></el-table-column>
      <el-table-column
        v-if="groupColumnSelectList.includes('goodsId')"
        label="商品名称"
        prop="goodsName"
      ></el-table-column>
      <el-table-column
        v-if="groupColumnSelectList.includes('goodsId')"
        label="条形码"
        prop="barcode"
      ></el-table-column>
      <el-table-column
        v-if="groupColumnSelectList.includes('goodsBrandId')"
        label="品牌"
        prop="goodsBrandName"
      ></el-table-column>
      <el-table-column
        v-if="groupColumnSelectList.includes('goodsTypeId')"
        label="商品分类"
        prop="goodsTypeName"
      ></el-table-column>
      <el-table-column
        v-if="groupColumnSelectList.includes('warehouseId')"
        label="仓库"
        prop="warehouseName"
      ></el-table-column>
      <el-table-column
        v-if="groupColumnSelectList.includes('supplierId')"
        label="供应商编码"
        prop="supplierCode"
      ></el-table-column>
      <el-table-column
        v-if="groupColumnSelectList.includes('supplierId')"
        label="供应商名称"
        prop="supplierName"
      ></el-table-column>
      <el-table-column
        v-if="
          groupColumnSelectList.includes('goodsId') &&
          groupColumnSelectList.includes('warehouseId')
        "
        label="成本价"
        prop="costTaxPrice"
      ></el-table-column>
      <el-table-column label="期初">
        <el-table-column label="数量" prop="beginGoodsCount"></el-table-column>
        <el-table-column label="箱数" prop="beginBoxCount"></el-table-column>
        <el-table-column
          label="含税金额"
          prop="beginTaxAmount"
        ></el-table-column>
        <el-table-column
          label="未税金额"
          prop="beginNoTaxAmount"
        ></el-table-column>
      </el-table-column>
      <el-table-column label="采购">
        <el-table-column
          label="入库数量"
          prop="buyInGoodsCount"
        ></el-table-column>
        <el-table-column
          label="入库箱数"
          prop="buyInBoxCount"
        ></el-table-column>
        <el-table-column
          label="入库含税金额"
          prop="buyInTaxAmount"
        ></el-table-column>
        <el-table-column
          label="入库未税金额"
          prop="buyInNoTaxAmount"
        ></el-table-column>
        <el-table-column
          label="出库数量"
          prop="buyOutGoodsCount"
        ></el-table-column>
        <el-table-column
          label="出库箱数"
          prop="buyOutBoxCount"
        ></el-table-column>
        <el-table-column
          label="出库含税金额"
          prop="buyOutTaxAmount"
        ></el-table-column>
        <el-table-column
          label="出库未税金额"
          prop="buyOutNoTaxAmount"
        ></el-table-column>
      </el-table-column>
      <el-table-column label="销售">
        <el-table-column
          label="入库数量"
          prop="saleInGoodsCount"
        ></el-table-column>
        <el-table-column
          label="入库箱数"
          prop="saleInBoxCount"
        ></el-table-column>
        <el-table-column
          label="入库含税金额"
          prop="saleInTaxAmount"
        ></el-table-column>
        <el-table-column
          label="入库未税金额"
          prop="saleInNoTaxAmount"
        ></el-table-column>
        <el-table-column
          label="出库数量"
          prop="saleOutGoodsCount"
        ></el-table-column>
        <el-table-column
          label="出库箱数"
          prop="saleOutBoxCount"
        ></el-table-column>
        <el-table-column
          label="出库含税金额"
          prop="saleOutTaxAmount"
        ></el-table-column>
        <el-table-column
          label="出库未税金额"
          prop="saleOutNoTaxAmount"
        ></el-table-column>
      </el-table-column>
      <el-table-column label="调拨">
        <el-table-column
          label="入库数量"
          prop="allotInGoodsCount"
        ></el-table-column>
        <el-table-column
          label="入库箱数"
          prop="allotInBoxCount"
        ></el-table-column>
        <el-table-column
          label="入库含税金额"
          prop="allotInTaxAmount"
        ></el-table-column>
        <el-table-column
          label="入库未税金额"
          prop="allotInNoTaxAmount"
        ></el-table-column>
        <el-table-column
          label="出库数量"
          prop="allotOutGoodsCount"
        ></el-table-column>
        <el-table-column
          label="出库箱数"
          prop="allotOutBoxCount"
        ></el-table-column>
        <el-table-column
          label="出库含税金额"
          prop="allotOutTaxAmount"
        ></el-table-column>
        <el-table-column
          label="出库未税金额"
          prop="allotOutNoTaxAmount"
        ></el-table-column>
      </el-table-column>
      <el-table-column label="损益">
        <el-table-column label="数量" prop="incomeGoodsCount"></el-table-column>
        <el-table-column label="箱数" prop="incomeBoxCount"></el-table-column>
        <el-table-column label="含税金额" prop="incomeTaxAmount"></el-table-column>
        <el-table-column
          label="未税金额"
          prop="incomeNoTaxAmount"
        ></el-table-column>
      </el-table-column>
      <el-table-column label="期末">
        <el-table-column label="数量" prop="endGoodsCount"></el-table-column>
        <el-table-column label="箱数" prop="endBoxCount"></el-table-column>
        <el-table-column label="含税金额" prop="endTaxAmount"></el-table-column>
        <el-table-column
          label="未税金额"
          prop="endNoTaxAmount"
        ></el-table-column>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <pagination />
  </div>
</template>

<script>
import crudReportMonthlyinventory from "@/api/erp/reportMonthlyinventory";
import CRUD, { presenter, header, form, crud } from "@crud/crud";
import rrOperation from "@crud/RR.operation";
import crudOperation from "@crud/CRUD.operation";
import udOperation from "@crud/UD.operation";
import pagination from "@crud/Pagination";
import { getBasGoodsTypeTree } from "@/api/erp/basGoodsType";
import Treeselect from "@riophae/vue-treeselect";
import { publicListKey } from "@/utils/key";
import { tablemixins } from "@/mixins/tablemixins";
import jTableColumnConfig from "@/components/jTableColumnConfig/jTableColumnConfig";
let thisDate = new Date().getFullYear() + "-" + (new Date().getMonth() + 1);
// crud交由presenter持有
const defaultCrud = CRUD({
  title: "分月进销存报表",
  optShow: {
    add: false,
    edit: false,
    del: false,
    download: false,
    leadingIn: false,
    enable: false,
    disable: false,
    pass: false,
    reject: false,
    invalid: false,
    recover: false,
    downloadDetail: false,
    print: false,
    printDetail: false,
  },
  query: {
    // customerIds: "",
    warehouseIds: "",
    goodsIds: "",
    goodsBrandIds: "",
    groupColumns: "goodsId,warehouseId",
    supplierIds: "",
    goodsTypeIds: "",
    month: thisDate.split("-")[1],
    year: thisDate.split("-")[0],
  },
  queryOnPresenterCreated:false,
  url: "/api/ReportMonthlyStock",
  sort: "id,desc",
  crudMethod: { ...crudReportMonthlyinventory },
});
const defaultForm = {
  // customerIds: null,
};
export default {
  name: "ReportMonthlyinventory",
  components: {
    pagination,
    crudOperation,
    rrOperation,
    udOperation,
    Treeselect,
    jTableColumnConfig,
  },
  mixins: [
    presenter(defaultCrud),
    header(),
    form(defaultForm),
    crud(),
    publicListKey,
    tablemixins,
  ],
  mounted() {
    this.crud.props.searchToggle = false;
  },
  created() {
    getBasGoodsTypeTree({ size: 999 }).then((res) => {
      this.areaList = res.data;
    });
  },
  data() {
    return {
      areaList: [],
      allotInBoxCount: 0,
      allotInGoodsCount: 0,
      allotInNoTaxAmount: 0,
      allotInTaxAmount: 0,
      allotOutBoxCount: 0,
      allotOutGoodsCount: 0,
      allotOutNoTaxAmount: 0,
      allotOutTaxAmount: 0,
      barcode: " ",
      beginBoxCount: 0,
      beginGoodsCount: 0,
      beginNoTaxAmount: 0,
      beginTaxAmount: 0,
      buyInBoxCount: 0,
      buyInGoodsCount: 0,
      buyInNoTaxAmount: 0,
      buyInTaxAmount: 0,
      buyOutBoxCount: 0,
      buyOutGoodsCount: 0,
      buyOutNoTaxAmount: 0,
      buyOutTaxAmount: 0,
      costTaxPrice: 0,
      endBoxCount: 0,
      endGoodsCount: 0,
      endNoTaxAmount: 0,
      endTaxAmount: 0,
      goodsBrandCode: " ",
      goodsBrandId: 0,
      goodsBrandName: " ",
      goodsCode: " ",
      goodsId: 0,
      goodsName: " ",
      goodsTypeCode: " ",
      goodsTypeId: 0,
      goodsTypeIds: [],
      goodsTypeName: " ",
      incomeBoxCount: 0,
      incomeGoodsCount: 0,
      incomeNoTaxAmount: 0,
      incomeTaxAmount: 0,
      saleInBoxCount: 0,
      saleInGoodsCount: 0,
      saleInNoTaxAmount: 0,
      saleInTaxAmount: 0,
      saleOutBoxCount: 0,
      saleOutGoodsCount: 0,
      saleOutNoTaxAmount: 0,
      saleOutTaxAmount: 0,
      supplierCode: " ",
      supplierId: 0,
      supplierName: " ",
      warehouseCode: " ",
      warehouseId: 0,
      warehouseName: " ",
      date: thisDate,
      permission: {
        add: ["admin", "reportMonthlyinventory:add"],
        edit: ["admin", "reportMonthlyinventory:edit"],
        del: ["admin", "reportMonthlyinventory:del"],
        import: ["admin", "reportMonthlyinventory:import"],
        export: ["admin", "reportMonthlyinventory:export"],
        copy: ["admin", "reportMonthlyinventory:copy"],
        upload: ["admin", "reportMonthlyinventory:upload"],
        download: ["admin", "reportMonthlyinventory:download"],
      },
      rules: {
        goodsId: [
          { required: true, message: "商品id不能为空", trigger: "blur" },
        ],
      },
      groupColumnSelectList: ["goodsId", "warehouseId"],
      groupColumn: ["goodsId", "warehouseId"],
      groupColumnList: [
        {
          label: "商品",
          value: "goodsId",
        },
        {
          label: "品牌",
          value: "goodsBrandId",
        },
        {
          label: "供应商",
          value: "supplierId",
        },
        {
          label: "商品分类",
          value: "goodsTypeId",
        },
        {
          label: "仓库",
          value: "warehouseId",
        },
      ],
    };
  },
  watch: {
    goodsTypeIds(n) {
      if (!n.length) {
        this.query.goodsTypeIds = null;
      }
    },
  },
  methods: {
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeRefresh]() {
      return true;
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {},
    getChange(val) {
      this.groupColumnSelectList = val;
      let groupColumn = this.groupColumnSelectList.join(",");
      this.$set(this.query, "groupColumns", groupColumn);
    },
    resetQuery() {
      this.goodsTypeIds = [];
      this.goodsBrandIds = [];
      this.customerTypeIds = [];
      this.warehouseIds = [];
      // this.customerIds = [];
      this.goodsIds = [];
      // this.groupColumn = [];
      // this.groupColumnSelectList = [];
      this.crud.resetQuery();
    },
    queryReport() {
      if (!this.date) {
        this.$message("请先选择年月");
      } else {
        this.query.year = this.date.split("-")[0];
        this.query.month = this.date.split("-")[1];

        
        this.crud.toQuery();
        this.crud.props.searchToggle = false;
      }
    },
     getgoodsType(val) {
      let str = ''
      val.forEach(item=>{
        const itemNode = this.getTreeName(this.areaList,item)
        str = this.getNode(itemNode,str)
      })
      this.query.goodsTypeIds = str
      this.query.goodsTypeIds = this.query.goodsTypeIds.length
        ? this.query.goodsTypeIds.join(",")
        : "";
        console.log('99999',this.query.goodsTypeIds)
    },
    getTreeName(treeList,id){
      let _this=this
      for (let i = 0; i < treeList.length; i++) {
        let treeItem=treeList[i]
        if(treeItem.id===id){
          return treeItem
        }else{
          if(treeItem.children && treeItem.children.length>0){
            let res=_this.getTreeName(treeItem.children,id)
            if(res){
              return res
            }
          }
        }
      }
    },
    getNode(node, str) {
      if (node.children) {
        for (let i = 0; i < node.children.length; i++) {
          str = this.getNode(node.children[i], str);
        }
      }
      return (str += node.id + ",");
    },
    normalizer(node) {
      //去掉children=[]的children属性
      if (node.children == null || node.children.length == 0) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
    getGroupColumn() {
      let str = "";
      for (let i = 0; i < this.groupColumnSelectList.length; i++) {
        const group = this.groupColumnList.find(
          (val) => val.value == this.groupColumnSelectList[i]
        );
        str +=
          i < this.groupColumnSelectList.length
            ? `${group.label}:${group.value}|`
            : `${group.label}:${group.value}`;
      }
      console.log("333222", str);
      return str;
    },
  },
};
</script>

<style scoped>
.table-img {
  display: inline-block;
  text-align: center;
  background: #ccc;
  color: #fff;
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
  width: 32px;
  height: 32px;
  line-height: 32px;
}
.flex {
  display: flex;
}
.fow-reverse {
  flex-direction: row-reverse;
}
::v-deep .el-table--border th.el-table__cell{
  border-bottom: 1px solid #000;
}
.flex-wrap{
    flex-wrap: wrap;
}
</style>
